package com.shuyuntu.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shuyuntu.common.controller.JdbcController;
import com.shuyuntu.entity.User;

@Controller
@RequestMapping("/user")
public class UserController {

	/**
	 * 注册
	 * 
	 * @param user
	 * @throws Exception
	 */
	@RequestMapping("/register")
	@ResponseBody
	public void register(User user) throws Exception {
		Connection conn = JdbcController.getConnection();
		Statement stmt = conn.createStatement();// 创建一个Statement对象
		// 查询有没有一样的名称
		// select count(B) from A where B = 01
		String sqll = "select count(F_USERNAME) from th_user where F_USERNAME =" + "'" + user.getUserName() + "'";
		System.err.println("sqll:" + sqll);
		ResultSet rs1 = stmt.executeQuery(sqll);
		ResultSetMetaData rst = rs1.getMetaData();
		if (rs1.next()) {
			int column = rst.getColumnCount();
			for (int i = 1; i <= column; i++) {
				System.err.println("已有个数:" + rs1.getString(i));

			}
		}

		// 查询最大值id
		ResultSet rs = stmt.executeQuery("select max(F_ID) from th_user");
		ResultSetMetaData m = rs.getMetaData();
		int columns = m.getColumnCount();
		while (rs.next()) {
			for (int i = 1; i <= columns; i++) {

				int max = Integer.valueOf(rs.getInt(i));
				System.err.println("max：" + max);
				user.setId(max + 1);

			}
		}

		// 插入数据
		String sql = "insert into th_user (F_USERNAME,F_POSS,F_ID)values(" + "'" + user.getUserName() + "','"
				+ user.getPoss() + "'," + user.getId() + ")";
		System.err.println(sql);
		stmt.executeUpdate(sql);// 执行sql语句
	}

	/**
	 * 登陆
	 * 
	 * @param user
	 * @throws Exception
	 */
	@RequestMapping("/land")
	@ResponseBody
	public void land(User user) throws Exception {

		String userName =user.getUserName();
		String poss = user.getPoss();
	
		 findByUserName(userName, poss); 

	}

	@RequestMapping("/lands")
	@ResponseBody
	public String findByUserName(String userName, String poss) throws Exception {
		Connection conn = JdbcController.getConnection();
		Statement stmt = conn.createStatement();// 创建一个Statement对象
		String sql = "select * from th_user where F_USERNAME =" + "'" + userName + "'";
		System.err.println("sql:" + sql);
		ResultSet rs = stmt.executeQuery(sql);
		while (rs.next()) {
			
			if (userName.equals(rs.getString(1)) && poss.equals(rs.getString(2))) {
				return "登陆成功";
			} else {
				return "用户名或密码错误，请重新输入";
			}
		}
		return "用户名或密码错误，请重新输入！";
	}
}
